package com.bill.pokerbe.service;

import com.bill.pokerbe.config.Const;
import com.bill.pokerbe.model.Option;
import com.bill.pokerbe.model.OptionType;
import com.bill.pokerbe.model.Status;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PokerService {
    @Autowired
    private UserService userService;

    public void initGame() {
        userService.initGame();
    }

    public void startGame() {
        userService.startGame();
    }

    public Status heartBeat(String userId, String username) {
        return userService.getStatus(userId, username);
    }

    public String action(String userId, Option option) {
        boolean wanDianYiTiZhuRen = false;
        if (!userService.isGameStart()) {
            return "游戏未开始";
        }
        int userIndex = userService.getUserIndexByUserId(userId);
        if (userIndex < 0 || userIndex >= userService.getUserCount()) {
            return "找不到玩家信息";

        }
        if (userIndex != userService.getActionUserIndex()) {
            return "现在你不可操作";
        }
        if (!userService.isUserGaming(userIndex)) {
            return "玩家不在牌桌";
        }
        if (option.optionType == OptionType.跟注) {
            String result = userService.userBetting(userIndex, userService.getMoneyRound() - userService.getUserMoneyInRoundByUserIndex(userIndex));
            if (!"".equals(result)) {
                return result;
            }
        } else if (option.optionType == OptionType.加注) {
            boolean equalsGenZhu = userService.isUserEqualsGenZhu(userIndex, option.optionNum);//等于跟注

            String result = userService.userBetting(userIndex, option.optionNum);
            if (!"".equals(result)) {
                return result;
            }
            if (!equalsGenZhu) {
                userService.setNewMaster(userIndex);
            }
        } else if (option.optionType == OptionType.弃牌) {
            String result = userService.userStopGame(userIndex);
            if (!"".equals(result) && !Const.WanDianYiTiZhuRen.equals(result)) {
                return result;
            }
            if (Const.WanDianYiTiZhuRen.equals(result)) {
                wanDianYiTiZhuRen = true;
            }
        }
        if (userService.nextIsMaster(userIndex)) {
            userService.nextRound();
        }
        if (wanDianYiTiZhuRen) {
            userService.setNewMaster(userService.nextUserIndex(userService.getMasterIndex()));
        }
        userService.actionUserMoveNext();
        return "";
    }

    public String addMoney(String userId, int amount) {
        return userService.addMoney(userId, amount);
    }
}
